package com.dts.interceptor;

import com.alibaba.fastjson.JSON;
import com.dts.advice.R;
import com.dts.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("拦截器执行了");
        System.out.println("url:" + request.getRequestURI());
        if (request.getRequestURI().contains("login")
                ||request.getRequestURI().contains("register")
        ){
            return true;
        }else {
            String token = request.getHeader("token");
            if (token == null){
                // 设置响应头
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(JSON.toJSONString(R.error(401,"没权限")));
                return false;
            }
            String user = JwtUtil.validateToken(token);
            if (user == null){
                // 设置响应头
                response.setContentType("application/json;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(JSON.toJSONString(R.error(401,"没权限")));
                return false;
            }
            System.out.println(user);
        }
        return true;
    }
}
